package com.gongjie.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gongjie.blog.dao.mapper.ArticleMapper;
import com.gongjie.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author jiegong
 * @create 2021-09-26 16:08
 */
@Service
public class ThreadService {

    // 在线程池中执行， 不影响主线程
    @Async("taskExecutor") // 使用config中定义的线程池
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        int viewCounts = article.getViewCounts(); // 得到当前阅读数
        Article articleUpdate = new Article(); // 新建一个文章对象， 只改变阅读数
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaQueryWrapper<Article> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Article::getId, article.getId()); // 找到那个文章
        // 线程安全的保险
        updateWrapper.eq(Article::getViewCounts, viewCounts);  // 修改之前检查一遍是否有其他线程修改了阅读数
        articleMapper.update(articleUpdate, updateWrapper);

//        try {
//            Thread.sleep(5000);
//            System.out.println("AAAAAAAAAAA");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
